﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace OINS
{
    class Client2
    {
        List<String> askers = new List<String>();
        public NetworkStream streamToServer;
        public System.IO.StreamWriter writer;
        System.IO.StreamReader Reader;
        TcpClient tcpSocket;
        public string serverName;
        int bytesRead;
        String response;
        String file;
        public String ip;
        String askerSearch;
        private byte[] buffer;
        String sciezka;
   
        public Stream inputstream;

   



        public Client2(String serverName)
        {
            this.serverName = serverName;
            Console.WriteLine("Polaczenie z {0}", serverName);
        }
        public void LoadTheDir()
        {
            try
            {
                FileInfo list = new FileInfo("dir.txt");
                StreamReader stream = list.OpenText();
                sciezka = stream.ReadLine();
                stream.Close();
            }
            catch (System.IO.IOException)
            {
                sciezka = "";
            }
        }
        public bool Routing(String dest)
        {
            writer.WriteLine("ROUTING");
            streamToServer.Flush();
            if (response == "ROUTING-OK")
            {
                writer.WriteLine(dest);
                writer.Flush();
                return true;
            }
            return false;

        }




        public void Send(String dir, String filename)
        {
            writer.WriteLine("SENDING " + filename);
            writer.Flush();
            byte[] fileBuffer;
            Stream fileStream = File.OpenRead(dir+filename);
            long temp = fileStream.Length;
            int cos;
            do
            {
                fileBuffer = new byte[256];
                cos = fileStream.Read(fileBuffer, 0, 256);
                if (temp < 256)
                {
                    streamToServer.Write(fileBuffer, 0, (int)temp);
                    temp = 0;
                }
                else
                {
                    streamToServer.Write(fileBuffer, 0, 256);
                    temp -= 256;
                }
                Console.WriteLine(temp);
            } while (temp > 0);
            System.Console.WriteLine("jestem tu");
            fileStream.Close();
        }

        public void SendPass(String filename, String odbiorca, List<String> downers)
        {
            String tempor = "";
            for (int i = 0; i < downers.Count(); i++)
            {
                if (i == downers.Count())
                    tempor += downers[i];
                else
                    tempor += downers[i] + " ";
            }
            writer.WriteLine("ROUTING " + odbiorca + " " + filename + " " + tempor);
            writer.Flush();
            response = Reader.ReadLine();
            if (response == "ROUTING-OK")
            {
                writer.WriteLine("GO");
                writer.Flush();
                byte[] fileBuffer;
                Stream fileStream = File.OpenRead(filename);
                long temp = fileStream.Length;
                int cos;
                do
                {
                    fileBuffer = new byte[256];
                    cos = fileStream.Read(fileBuffer, 0, 256);
                    if (temp < 256)
                    {
                        streamToServer.Write(fileBuffer, 0, (int)temp);
                        temp = 0;
                    }
                    else
                    {
                        streamToServer.Write(fileBuffer, 0, 256);
                        temp -= 256;
                    }
                    Console.WriteLine(temp);
                } while (temp > 0);
              
                fileStream.Close();
            }
        }


        public void PushSearch(String filename, List<String> askers)
        {

            askers = askers;
            askers.Add(serverName);
            String tempor = "";
            for (int i = 0; i < askers.Count; i++)
            {

                tempor += " " + askers.ElementAt(i);
            }
            System.Console.WriteLine("CL: tempor ----------" + tempor);
            file = filename;
            writer.WriteLine("Search" + tempor);
            writer.Flush();
            response = Reader.ReadLine();
            System.Console.WriteLine("CL: PUSHSEARCH");
            if (response == "SEARCH-OK")
            {
                System.Console.WriteLine("CL: search-ok");
                writer.WriteLine(filename);
                writer.Flush();
                response = Reader.ReadLine();
                if (response == "DOWNLOADING")
                {
                    System.Console.WriteLine("CL: downloading");
                    writer.WriteLine("START");
                    writer.Flush();
                    
                }

            }
            if (response == "NOTFOUND")
            {
                MessageBox.Show("NOT FOUND");
            }
            System.Console.WriteLine("CL: KONIEC");
        }
        public void Read(String filename)
        {
            LoadTheDir();
            Stream fileStream = File.OpenWrite(sciezka +"/"+ filename);
            byte[] fileBuffer = new byte[256];
            streamToServer.ReadTimeout = 2;
            int cos;
            do
            {
                try
                {
                    cos = streamToServer.Read(fileBuffer, 0, 256);
                }
                catch (System.IO.IOException)
                {
                    cos = 0;
                }

                System.Console.WriteLine("to jest cos {0}", cos);
                fileStream.Write(fileBuffer, 0, cos);
            } while (cos > 0);
            System.Console.WriteLine("dziala ");

            fileStream.Close();

        }

 
        public void Disconnect()
        {

            String response;
            writer.WriteLine("DISCONNECTING");
            writer.Flush();
            response = Reader.ReadLine();
            if (response == "OK-DISCONNECT")
            {
                writer.Close();
                Reader.Close();
                streamToServer.Close();
                tcpSocket.Close();
                tcpSocket = null;
            }

        }
        public bool Connect()
        {
            try
            {
                tcpSocket = new TcpClient(serverName, 65000);
                streamToServer = tcpSocket.GetStream();
                ip = serverName;
                buffer = new byte[256];
                Console.WriteLine("KLIENCIK IP TO: " + ip);

                writer = new System.IO.StreamWriter(streamToServer);
                Reader = new System.IO.StreamReader(streamToServer);
                String response;
                writer.WriteLine("Hello aP2P Server");
                writer.Flush();
                response = Reader.ReadLine();
                if (response == "Hello aP2P Client")
                {
                    writer.WriteLine("Connection established");
                    writer.Flush();
                    return true;
                }
                else
                    return false;
            }
            catch (System.Net.Sockets.SocketException)
            {
                MessageBox.Show("Disconnected");
                return false;
            }
        }


        public void Run()
        {
            Connect();
            streamToServer.Close();
        }
    }
}

